<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>Document</title>
    <style>
        #inp{
            border: 1px solid #ccc;
        }
    </style>
</head>

<body>
    <input id="file" type="file" multiple hidden>
    <button id="upload">上传图片</button>
    <div id="inp" type="text" contenteditable="true"></div>
    <button id="btn">提交</button>
    <div id="list"></div>
    <script>
        var inp = document.querySelector('#inp');
        var btn = document.querySelector('#btn');
        var list = document.querySelector('#list');
        var upload = document.querySelector('#upload');
        var file =document.querySelector('#file');
        var socket = new WebSocket('ws://localhost:4080');

        upload.onclick = function(){
            file.click();
        }

        file.onchange = function(){

            console.log(this.files);
            console.log(this.files[0]);
            var f = this.files[0];
            var fr = new FileReader();
            fr.readAsDataURL(f);  
            console.log(fr);
            fr.onload = function(){
                
                socket.send(JSON.stringify({
                    name:'浩',
                    msg:inp.innerHTML,
                    img:fr.result
                }))
            }


        }


        socket.onopen = function(){
            console.log('socktet open');          
        }
        btn.onclick = function(e){
            socket.send(JSON.stringify({
                name:'浩',
                msg:inp.innerHTML,

            }))
        }
        socket.onmessage = function(e){
            console.log(e.data);
            var p = document.createElement('p');
            var data = JSON.parse(e.data);
            p.innerHTML = `<span>${data.name}:</span>
            <span>${data.msg}</span>`;
            if(data.img) p.innerHTML += `<img src=${data.img}>`;
            list.append(p);

        }
        socket.onclose = function(event){
            console.log('close');
        }
        //socket.close();
        

    </script>

</body>

</html>